import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_tv_widgets/resources/kq_theme_colors.dart';
import 'package:kq_flutter_tv_widgets/widgets/tagView/kq_icon_tag.dart';

class KqAutoColumnFlow extends StatefulWidget {
  ///水平方向item间距
  final double? spacing;

  ///竖直方向item间距
  final double? runSpacing;

  ///右边文本颜色，默认：text59
  final Color? textColor;

  ///文案大小默认14
  final double? fontSize;

  /// leftText大小
  final double? leftTextFontSize;

  ///icon宽默认15,viewType=3时，改宽为左边问的最大宽度
  final double? iconWidth;

  ///样式，1:图左文右，2:图右文左，3:文本加文本格式，左边文本的宽高使用icon的宽高，其中宽为最大宽度默认为30
  final int? viewType;

  /// 个数
  final int totalCount;

  /// 行数
  final int Function()? rowCountCallback;

  ///每行的列数
  final int Function(int row)? renderCrossAxisCountCallback;

  ///icon
  final String Function(int row, int column)? renderIconPathCallback;

  /// leftText
  final String Function(int row, int column)? renderLeftTextCallback;

  ///Text
  final String Function(int row, int column)? renderTextCallback;

  ///Widget
  final Widget? Function(int row, int column)? renderWidgetCallback;

  ///Text行数
  final int Function(int row, int column) renderTextMaxLineCallback;

  ///背景色,默认白色
  final Color? backgroundColor;
  const KqAutoColumnFlow({
    super.key,
    required this.totalCount,
    required this.renderCrossAxisCountCallback,
    required this.renderTextCallback,
    required this.rowCountCallback,
    required this.renderTextMaxLineCallback,
    this.renderIconPathCallback,
    this.renderLeftTextCallback,
    this.viewType,
    this.renderWidgetCallback,
    this.backgroundColor = KqThemeColors.bgWhite,
    this.spacing = 4,
    this.runSpacing = 9,
    this.textColor = KqThemeColors.text59,
    this.fontSize,
    this.leftTextFontSize,
    this.iconWidth,
  });

  @override
  State<KqAutoColumnFlow> createState() => _KqAutoColumnFlowState();
}

class _KqAutoColumnFlowState extends State<KqAutoColumnFlow> {
  final GlobalKey _wrapKey = GlobalKey();
  double widgetWidth = 0;

  @override
  void initState() {
    super.initState();
    //监听widget绘制完成，计算每个item的宽度
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      final RenderBox? supperView =
          _wrapKey.currentContext!.findRenderObject() as RenderBox?;
      var size = supperView?.size;
      //获取Row的宽度
      widgetWidth = size?.width ?? 0;
      setState(() {});
    });
  }

  double getItemContainerWidth(int count) {
    //每个item的宽度=Row的宽度-每个item的间距(widget.spacing * (widget.crossAxisCount - 1))-容错(可能小数点后面位数太多导致超屏(widget.crossAxisCount - 1))
    var width = (widgetWidth - widget.spacing! * (count - 1) - (count - 1));
    if (width > 0) {
      return width;
    }
    return widgetWidth;
  }

  List<Widget> renderItems() {
    //默认
    int total = 0;
    if (widget.totalCount > 0) {
      total = widget.totalCount;
    }
    int row = 0;
    if (widget.rowCountCallback != null) {
      row = widget.rowCountCallback!();
    }
    List<Widget> items = [];
    //总数 总行数
    for (var i = 0; i < row; i++) {
      int column = widget.renderCrossAxisCountCallback!(i);
      double viewWidth = getItemContainerWidth(column) / column;
      for (var j = 0; j < column; j++) {
        //一行几个
        if (items.length >= total) {
          break;
        }
        String? title = widget.renderIconPathCallback?.call(i, j);
        if (widget.renderLeftTextCallback != null) {
          title = widget.renderLeftTextCallback?.call(i, j);
        }
        String text = widget.renderTextCallback!(i, j);
        int lines = widget.renderTextMaxLineCallback(i, j);
        Widget? custom;
        if (widget.renderWidgetCallback != null) {
          custom = widget.renderWidgetCallback!(i, j);
        }
        if (custom != null) {
          items.add(
            KqIconTagView(
              crossAxisAlignment: lines > 1
                  ? CrossAxisAlignment.start
                  : CrossAxisAlignment.center,
              iconPath: title,
              leftText: title,
              text: '',
              contentWidget: custom,
              maxLines: lines,
              viewType: widget.viewType ?? 3,
              iconWidth: widget.iconWidth,
              width: viewWidth,
              fontSize: widget.fontSize ?? 20.sp,
              leftFont: widget.leftTextFontSize ?? 20.sp,
              textColor: widget.textColor,
              leftTextColor: widget.textColor,
              backgroundColor: widget.backgroundColor,
            ),
          );
        } else {
          items.add(
            KqIconTagView(
              crossAxisAlignment: lines > 1
                  ? CrossAxisAlignment.start
                  : CrossAxisAlignment.center,
              iconPath: title,
              leftText: title,
              text: text,
              maxLines: lines,
              viewType: widget.viewType ?? 3,
              iconWidth: widget.iconWidth,
              width: viewWidth,
              fontSize: widget.fontSize ?? 20.sp,
              leftFont: widget.leftTextFontSize ?? 20.sp,
              textColor: widget.textColor,
              leftTextColor: widget.textColor,
              backgroundColor: widget.backgroundColor,
            ),
          );
        }
      }
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      key: _wrapKey,
      children: [
        Expanded(
            child: Wrap(
          crossAxisAlignment: WrapCrossAlignment.center,
          spacing: widget.spacing ?? 4.r,
          runSpacing: widget.runSpacing ?? 9.r,
          children: renderItems(),
        ))
      ],
    );
  }
}
